<template>
  <el-row>
    <el-col ref="myCol" v-loading="loading" :span="12" style="overflow: hidden;border: 1px solid #d1d3d7;padding: 10px;">
      <el-button icon="el-icon-refresh-left" circle @click="leftAngle" />
      <el-button icon="el-icon-refresh-right" circle style="float:right;" @click="rightAngle" />
      <canvas id="canvas" ref="canvas" width="840" height="700">
        <p>{{ $t('您的浏览器不支持canvas') }}</p>
      </canvas>
    </el-col>
    <el-col :span="12" style="padding-left: 10px;">
      <el-table ref="multipleTable" :data="sheetData.sheetData" border :height="tableHeight" @cell-click="quadPosition" @selection-change="handleSelectionChange">
        <!-- <el-table-column :label="$t('序号')" type="index" align="center" /> -->
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column :label="$t('科目名称')" align="center" prop="subjectName" :width="sheetData.columnList.length == 0? '' : 350">
          <template v-slot="scope">
            <template v-if="contain(scope.row,scope.$index) === 'warning'">

              <el-tag size="mini" class="small-tag" effect="dark" type="warning" style="cursor: pointer" @click="returnMatchingStr(scope.row)">
                <el-popover placement="top-start" title="以下系统科目与财报科目类似，供您参考" trigger="hover" :content="`${returnMatching(scope.row.subjectName)}`">
                  <i slot="reference" class="el-icon-question" />
                </el-popover>
              </el-tag>

            </template>
            <template v-else-if="contain(scope.row,scope.$index) === 'success'">
              <el-tag size="mini" class="small-tag" effect="dark" type="success"> <i class="el-icon-success" /></el-tag>
            </template>
            <template v-else>
              <el-tag size="mini" class="small-tag" effect="dark" type="danger"> <i class="el-icon-error" /></el-tag>
            </template>
            <!-- :class="contain(scope.row.subjectName) ? '' : 'font-color-red'" -->
            <el-autocomplete v-model="scope.row.subjectName" :fetch-suggestions="querySearch" :placeholder="$t('科目名称')" style="width: 90%" @focus="calcRatio" />
          </template>
        </el-table-column>
        <template v-for="(item,i) in sheetData.columnList">
          <el-table-column :key="`${item}${i}`" align="center" :prop="`amount${i}`" :width="sheetData.columnList.length > 2? 190 : '' ">
            <template v-slot:header>
              <!-- item.columnInfo -->
              <el-radio v-model="checked" :label="i+1" @change="checkedChange">{{ getColumnInfo(i) }}</el-radio>
            </template>
            <template v-slot="scope">
              <money v-model="scope.row.wordsMapLists[i]['amount'+i]" />
            </template>
          </el-table-column>
        </template>
      <!-- <el-table-column :label="getColumnInfo(checked)" align="center" prop="amount1" width="170">
          <template v-slot:header>
            <el-radio v-model="checked" :label="1" @change="checkedChange">{{ getColumnInfo(1) }}</el-radio>
          </template>
          <template v-slot="scope">
            <money v-model="scope.row.amount1" />
          </template>
        </el-table-column>
        <el-table-column :label="getColumnInfo(checked)" align="center" prop="amount2" width="170">
          <template slot="header">
            <el-radio v-model="checked" :label="2" @change="checkedChange">{{ getColumnInfo(2) }}</el-radio>
          </template>
          <template v-slot="scope">
            <money v-model="scope.row.amount2" />
          </template>
        </el-table-column> -->
      <!-- <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" fixed="right" width="50">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="text"
              icon="el-icon-delete"
              @click="deleteHandle(scope.row,scope.$index)"
            />
          </template>
        </el-table-column> -->
      </el-table>
      <div class="bottom_contain mt10">
        <div class="tag_contain">
          <el-tag class="small-tag" effect="dark" size="mini" type="success"><i class="el-icon-success" /></el-tag> 已匹配科目
          <el-tag class="small-tag" effect="dark" size="mini" type="warning"><i class="el-icon-question" /></el-tag> 待确认科目
          <el-tag class="small-tag" effect="dark" size="mini" type="danger"><i class="el-icon-error" /></el-tag> 无匹配科目
        </div>
        <!-- <div id="main" style="width:70px;height:70px" /> -->
        <pcwChartRatio ref="pcwChartRatio" :chart-data="matchingStatusRatio" :matching-ratio="matchingRatio" />
      </div>
    </el-col>
    <!-- 平衡科目抽屉 -->
    <!-- v-loading="drawerLoading" -->
    <el-drawer direction="rtl" :modal="false" :size="820" :show-close="false" :visible.sync="subjectDrawer" :destroy-on-close="true" :append-to-body="true" :close-on-click-modal="false" :close-on-press-escape="false" custom-class="ds-setting-drawer header-small-mb">
      <template #title>
        <div class="drawer-title">原始匹配
          <el-tooltip placement="bottom">
            <div slot="content">
              基于您提供的科目，系统将会与模板科目进行匹配。请在下方进行必要的修改。
            </div>
            <i class="el-icon-question" />
          </el-tooltip>
        </div>
        <div style="float: right">
          <el-button size="mini" @click="subjectDrawer=false">取消</el-button>
          <!-- <el-button size="mini" :type="showEmptyRows?'success':'warning'" @click="toggleEmptyRows">{{ buttonText }}</el-button> -->
          <el-button type="primary" size="mini" @click="balanceHandler">确定</el-button>

        </div>
      </template>
      <template #default>
        <el-table v-loading="matchLoading" border :data="tableData" style="width: 100%" :height="tableHeight1">
          <el-table-column prop="subjectName" label="原始-科目名称" />
          <el-table-column prop="date" label="模板-科目名称">
            <template v-slot="scope">
              <el-autocomplete v-model="scope.row.matchName" :fetch-suggestions="querySearch" :placeholder="$t('科目名称')" style="width: 80%" />
              <template v-if="scope.row.status==='warning'">
                <el-tag style="margin-left: 10px;" size="mini" class="small-tag" effect="dark" type="warning"> <i class="el-icon-question" /></el-tag>
              </template>
              <template v-else-if="scope.row.status==='success'">
                <el-tag style="margin-left: 10px;" size="mini" class="small-tag" effect="dark" type="success"> <i class="el-icon-success" /></el-tag>
              </template>
              <template v-else>
                <el-tag style="margin-left: 10px;" size="mini" class="small-tag" effect="dark" type="danger"> <i class="el-icon-error" /></el-tag>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </el-drawer>
  </el-row>
</template>

<script>
import {
  findSubjectNameByCompanyId,
  delDataBaseById,
  delDataBaseByIds
} from '@/api/company/pcw/pcwTempSubject'
import innerHeight from '@/mixins/innerHeight'
import {
  fabric
} from 'fabric'
import {
  getToken
} from '@/utils/auth'
import PcwChartRatio from '@/views/company/pcw/pcwChartRatio'

export default {
  name: 'Diff',
  components: {
    PcwChartRatio
  },
  mixins: [innerHeight],
  props: {
    sheetData: {
      type: Object,
      default: () => {}
    },
    disabled: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: undefined
    },
    companyId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      canvas: undefined,
      group: undefined,
      checked: 1,
      showTemp: true,
      enableAnimate: true,
      tempSubject: [],
      baseUrl: process.env.VUE_APP_BASE_API,
      loading: false,
      angle: 0,
      prevImageUrl: undefined,
      colWidth: 800,
      matchingStatusRatio: {
        success: 0,
        warning: 0,
        danger: 0
      },
      matchingRatio: 0, // 已匹配科目百分比
      tempSubjectName: [], // 模板科目名字相似度用到的
      defColumn: ['本期金额', '上期金额'],
      multipleSelection: [],
      autoHeight: 700,
      prePosition: 18, // 上一次位置
      offestIndex: 0,
      subjectDrawer: false,
      tableData: [],
      matchLoading: false,
      showEmptyRows: true, // 初始状态为展示空行
      cacheTable: this.sheetData.sheetData
    }
  },
  computed: {
    buttonText() {
      return this.showEmptyRows ? '移除空行' : '展现空行'
    },
    tableHeight() {
      return this.innerHeight - 200
    },
    tableHeight1() {
      return this.innerHeight - 100
    }
  },
  mounted() {
    this.supportCanvas()
    this.load()
    findSubjectNameByCompanyId(this.companyId, this.type).then(res => {
      this.tempSubject = res.data.map(item => {
        return {
          'value': item
        }
      })
      this.tempSubjectName = res.data
    })
    // console.log('this.sheetData', this.sheetData)
    // this.initCharts()
    this.calculateTableHeight()
    // window.addEventListener('resize', this.calculateTableHeight)

    window.addEventListener('resize', () => {
      var height = window.innerHeight - 200
      this.canvas.setHeight(height)
    }, false)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight)
  },
  methods: {
    init() {
      this.checked = 1
      if (this.disabled) {
        this.checked = this.sheetData.checked
      } else {
        this.sheetData.checked = this.checked
      }
      this.angle = 0
      const canvas = this.canvas
      canvas.clear().renderAll()
      this.loading = true
      const getImageUrl = this.baseUrl + '/pcw/pcwDataMain/getImageByName/' + this.sheetData.imageNames[0] + '?Authorization=Bearer ' + getToken()
      this.prevImageUrl = getImageUrl
      // const rect = new fabric.Rect({
      //   stroke: 'red',
      //   strokeWidth: 5,
      //   fill: 'rgba(0,0,0,0)'
      // })
      fabric.Image.fromURL(getImageUrl, (oImg) => {
        oImg.hasControls = false
        canvas.sendToBack(oImg)
        const group = new fabric.Group([oImg], {
          hasControls: false,
          originX: 'center',
          originY: 'center',
          objectCaching: false
        })
        group.setCoords()
        canvas.add(group)
        if (group.width > canvas.width) {
          canvas.setZoom(0.35)
        }
        this.group = group
        canvas.renderAll()
        this.initCharts()
        this.loading = false
      })
    },
    supportCanvas() {
      if (this.$refs.canvas.getContext) {
        console.log('你的浏览器支持Canvas!')
      } else {
        console.log('你的浏览器不支持Canvas!')
      }
    },
    load() {
      const ref = this.$refs.canvas
      this.canvas = new fabric.Canvas(ref, {
        preserveObjectStacking: true,
        selection: false,
        height: window.innerHeight - 200
      })
      const canvas = this.canvas
      canvas.on('mouse:wheel', function(opt) {
        const delta = opt.e.deltaY
        let zoom = canvas.getZoom()
        zoom *= 0.999 ** delta
        if (zoom > 20) zoom = 20
        if (zoom < 0.01) zoom = 0.01
        canvas.setZoom(zoom)
        opt.e.preventDefault()
        opt.e.stopPropagation()
      })

      // 监听点击事件
      canvas.on('mouse:down', function(event) {
        var pointer = canvas.getPointer(event.e)
        var posX = pointer.x
        var posY = pointer.y
        console.log(posX + ', ' + posY)
      })
    },
    quadPosition(row, column) {
      if (row.pageIndex === undefined || row.pageIndex === null) {
        return
      }
      let quadArray = []
      const canvas = this.canvas
      const group = this.group
      const groupObjects = group.getObjects()
      const getImageUrl = this.baseUrl + '/pcw/pcwDataMain/getImageByName/' + this.sheetData.imageNames[row.pageIndex] + '?Authorization=Bearer ' + getToken()
      if (getImageUrl !== this.prevImageUrl) {
        groupObjects.forEach(item => {
          if (item instanceof fabric.Image) {
            this.loading = true
            item.setSrc(getImageUrl, () => {
              item.set('dirty', true)
              canvas.renderAll()
              this.loading = false
            })
          }
        })
        this.prevImageUrl = getImageUrl
      }
      try {
        if (column.property === 'subjectName') {
          if (row['subjectNameQuad']) {
            quadArray = row['subjectNameQuad'].split(',')
          } else {
            return
          }
        } else if (this.containsNumber(column.property)) {
          const columnIndex = this.getNumber(column.property)
          const quad = row.wordsMapLists[columnIndex]['amountQuad' + columnIndex]
          if (quad != null && quad !== '') {
            quadArray = row.wordsMapLists[columnIndex]['amountQuad' + columnIndex].split(',')
          } else {
            return
          }
        } else {
          return
        }
      } catch (e) {
        console.log(e)
        return
      }
      if (quadArray[0] === '0' && quadArray[1] === '0' && quadArray[2] === '0' && quadArray[3] === '0') {
        return
      }
      const x1 = quadArray[0]
      const y1 = quadArray[1]
      const x2 = quadArray[2]
      const y2 = quadArray[3]
      const x3 = quadArray[4]
      const y3 = quadArray[5]
      const x4 = quadArray[6]
      const y4 = quadArray[7]
      const aCoords = {
        tl: new fabric.Point(x1, y1),
        tr: new fabric.Point(x2, y2),
        br: new fabric.Point(x3, y3),
        bl: new fabric.Point(x4, y4)
      }
      canvas.setZoom(0.7)
      const x = x1 > canvas.width - 100 ? (group.width / 2) - (x1 / 1.7) : (group.width / 2)
      let y = 0
      // 找出大于2000 的第一个元素
      for (let i = 0; i < this.sheetData.sheetData.length; i++) {
        const el = this.sheetData.sheetData[i]
        if (el['subjectNameQuad']) {
          const subjectNameQuadArr = el['subjectNameQuad'].split(',')
          if (subjectNameQuadArr.length > 0) {
            const offest = subjectNameQuadArr[1]
            if (offest > 2000) {
              this.offestIndex = el['indexQuad']
              break
            }
          }
        }
      }
      if (y1 > 2000) {
        // 上边界的空白区域
        // const marginTop = this.sheetData.sheetData[0]['subjectNameQuad'].split(',')[0]
        // const size = this.sheetData.sheetData.length
        // const avgSize = (group.height - marginTop * 2) / size
        // const roundedAvgSize = Math.ceil(avgSize)
        // console.log('roundedAvgSize', roundedAvgSize)
        const thisIndex = row.indexQuad - this.offestIndex
        const offest = this.prePosition * thisIndex
        y = y1 > canvas.height - 100 ? (group.height / 2) - (y1 / 1.7) - offest : (group.height / 2)
      } else {
        y = y1 > canvas.height - 100 ? (group.height / 2) - (y1 / 1.7) : (group.height / 2)
      }
      // const distanceFromCenter = Math.sqrt(Math.pow(x1 - canvas.width / 2, 2) + Math.pow(y1 - canvas.height / 2, 2))
      // const scaleFactor = (distanceFromCenter < 100) ? (1.7 * (100 - distanceFromCenter) / 100) : 1.7
      // const x = x1 > canvas.width - 100 ? (group.width / 2) - (x1 / scaleFactor) : (group.width / 2)
      // const y = y1 > canvas.height - 100 ? (group.height / 2) - (y1 / scaleFactor) - 50 : (group.height / 2)
      group.animate({
        'left': x,
        'top': y
      }, {
        onChange: canvas.renderAll.bind(canvas),
        duration: 400,
        onComplete: () => {
          group.setCoords()
          if (group.item(1)) {
            group.remove(group.item(1))
          }
          addWithUpdate()
        }
      })

      function addWithUpdate() {
        // 偏移量
        const offset = 3
        group.addWithUpdate(new fabric.Rect({
          left: parseInt(x1) + group.left - (group.width / 2) - offset,
          top: parseInt(y1) + group.top - (group.height / 2) - offset,
          width: (new fabric.Point(aCoords.tl.x, aCoords.tl.y).distanceFrom(aCoords.tr)) + offset,
          height: (new fabric.Point(aCoords.tl.x, aCoords.tl.y).distanceFrom(aCoords.bl)) + offset,
          stroke: 'red',
          strokeWidth: 5,
          fill: 'rgba(0,0,0,0)'
        }).setCoords())
        canvas.renderAll()
      }
    },
    leftAngle() {
      if (!this.enableAnimate) {
        return
      }
      this.enableAnimate = false
      const group = this.group
      const canvas = this.canvas
      this.angle -= 90
      group.animate('angle', '-=90', {
        onChange: function() {
          group.setCoords()
          canvas.renderAll()
        },
        duration: 400,
        onComplete: () => {
          group.addWithUpdate().setCoords()
          canvas.renderAll()
          this.enableAnimate = true
        }
      })
    },
    rightAngle() {
      if (!this.enableAnimate) {
        return
      }
      this.enableAnimate = false
      const group = this.group
      const canvas = this.canvas
      this.angle += 90
      group.animate('angle', '+=90', {
        onChange: function() {
          group.setCoords()
          canvas.renderAll()
        },
        duration: 400,
        onComplete: () => {
          group.addWithUpdate().setCoords()
          canvas.renderAll()
          this.enableAnimate = true
        }
      })
    },
    querySearch(queryString, cb) {
      var restaurants = this.tempSubject
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
      }
    },
    // contain(val) {
    //   return this.tempSubject.filter(item => {
    //     return item.value === val
    //   }).length > 0
    // },
    checkedChange(val) {
      this.sheetData.checked = val
    },
    deleteHandle(row, index) {
      const id = row.id
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return true
      }).then(() => {
        if (id !== undefined && id !== '' && id != null) {
          delDataBaseById(row.id)
        }
        this.sheetData.sheetData.splice(index, 1)
        this.calcRatio()
        return this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {})
    },
    getColumnInfo(activeIndex) {
      let value = ''
      if (activeIndex <= this.sheetData.columnList.length) {
        value = this.sheetData.columnList[activeIndex].columnInfo
      } else {
        value = this.defColumn[activeIndex]
      }
      return value
    },
    contain(row, index) {
      row['indexQuad'] = index
      const whitespaceRegex = /\s+/
      const val = row.subjectName
      const cleanVal = val.replace(/ /g, '')
      const matchStr = this.findMostSimilarCourse(val)
      if (matchStr === '') {
        row['matchStatus'] = 'danger'
        return 'danger'
      }
      const cleanMatchStr = matchStr.replace(/ /g, '')
      if (whitespaceRegex.test(val)) {
        if (cleanVal === matchStr) {
          row['matchStatus'] = 'warning'
          return 'warning'
        } else if (cleanMatchStr === val) {
          row['matchStatus'] = 'warning'
          return 'warning'
        }
      }

      if (whitespaceRegex.test(matchStr)) {
        if (cleanVal === matchStr) {
          row['matchStatus'] = 'warning'
          return 'warning'
        } else if (cleanMatchStr === val) {
          row['matchStatus'] = 'warning'
          return 'warning'
        }
      }
      if (this.isStringSimilar(val, matchStr)) {
        row['matchStatus'] = 'warning'
        return 'warning'
      }
      const f = this.tempSubject.some(item => item.value === val)
      row['matchStatus'] = f ? 'success' : 'danger'
      return f ? 'success' : 'danger'
    },
    isStringSimilar(str1, str2, threshold = 0.35) {
      if (!str1 || !str2) {
        return false
      }
      str1 = str1.replace(/\s+/g, '')
      str2 = str2.replace(/\s+/g, '')

      if (!str1.length || !str2.length) return false
      const similarity = this.compareTwoStrings(str1, str2)
      return (similarity > threshold && similarity < 1)
    },
    compareTwoStrings(str1, str2) {
      str1 = str1.replace(/\s+/g, '')
      str2 = str2.replace(/\s+/g, '')

      if (!str1.length && !str2.length) return 1
      if (!str1.length || !str2.length) return 0
      if (str1 === str2) return 1
      if (str1.length === 1 && str2.length === 1) return 0
      if (str1.length < 2 || str2.length < 2) return 0

      const firstBigrams = new Map()
      for (let i = 0; i < str1.length - 1; i++) {
        const bigram = str1.substr(i, 2)
        const count = firstBigrams.has(bigram)
          ? firstBigrams.get(bigram) + 1
          : 1

        firstBigrams.set(bigram, count)
      }

      let intersectionSize = 0
      for (let i = 0; i < str2.length - 1; i++) {
        const bigram = str2.substr(i, 2)
        const count = firstBigrams.has(bigram)
          ? firstBigrams.get(bigram)
          : 0

        if (count > 0) {
          firstBigrams.set(bigram, count - 1)
          intersectionSize++
        }
      }
      return (2.0 * intersectionSize) / (str1.length + str2.length - 2)
    },
    returnMatching(val) {
      return this.findMostSimilarCourse(val)
    },
    returnMatchingStr(row) {
      row.subjectName = this.findMostSimilarCourse(row.subjectName)
      this.calcRatio()
    },
    calcRatio() {
      let success = 0
      let warning = 0
      let danger = 0
      // 总数去掉 空值科目
      const tableSheetData = this.sheetData.sheetData.filter(item => {
        return item.subjectName && item.subjectName.trim() !== ''
      })
      for (let i = 0; i < tableSheetData.length; i++) {
        const item = this.sheetData.sheetData[i]
        if (item.matchStatus === 'success') {
          success++
        } else if (item.matchStatus === 'warning') {
          warning++
        } else if (item.matchStatus === 'danger') {
          danger++
        }
      }
      this.matchingStatusRatio = {
        success,
        warning,
        danger
      }
      const totalCount = success + warning + danger
      if (totalCount === 0) {
        this.matchingRatio = 0
      } else {
        const successRatio = (success / totalCount) * 100
        this.matchingRatio = Math.ceil(successRatio)
      }
    },
    findMostSimilarCourse(targetString) {
      let maxSimilarity = 0
      let mostSimilarCourse = ''
      if (!targetString) {
        return mostSimilarCourse
      }
      for (let i = 0; i < this.tempSubjectName.length; i++) {
        const similarity = this.compareTwoStrings(this.tempSubjectName[i], targetString)
        if (similarity > maxSimilarity) {
          maxSimilarity = similarity
          mostSimilarCourse = this.tempSubjectName[i]
        }
      }
      return mostSimilarCourse
    },
    initCharts() {
      if (this.sheetData.sheetData.length > 0) {
        this.sheetData.sheetData.map(e => {
          this.contain(e)
        })
        setTimeout(this.calcRatio, 800)
        // this.calcRatio()
      } else {
        this.matchingRatio = 0
      }
    },
    containsNumber(str) { // 这个字符串是否包含数字
      return /\d/.test(str)
    },
    getNumber(str) {
      const match = str.match(/\d+/)
      return match ? match[0] : null
    },
    calculateTableHeight() {
      const screenHeight = window.innerHeight
      const tableElement = document.querySelector('.el-table')
      const tableTop = tableElement.getBoundingClientRect().top
      this.autoHeight = screenHeight - tableTop - 30
      // const canvas = document.getElementById('canvas')
      // canvas.height = screenHeight - tableTop
      // console.log(' canvas.height', canvas.height)
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.$emit('receve', val, this.type)
    },
    // 批量删除
    multipleDelHandle() {
      const ids = []
      this.multipleSelection.forEach(e => {
        if (e.id !== undefined && e.id !== '' && e.id != null) {
          ids.push(e.id)
        }
      })
      this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(function() {
        return true
      }).then(() => {
        if (ids.length > 0) {
          const baseDTO = {
            ids: ids.toString()
          }
          delDataBaseByIds(baseDTO)
        }
        this.multipleSelection.sort((a, b) => a.indexQuad - b.indexQuad)
        this.multipleSelection.reverse().map(row => {
          this.sheetData.sheetData.splice(row.indexQuad, 1)
        })
        this.multipleSelection = []
        this.$refs.multipleTable.clearSelection()
        this.calcRatio()
        return this.msgSuccess(this.$t('删除成功'))
      }).catch(function() {})
    },
    balanceHandler() {
        const subjectMap = new Map()
        this.tableData.forEach(item => {
          const subjectName = item.subjectName
          subjectMap.set(subjectName, item)
        })
      if (!this.showEmptyRows) { // 隐藏空行
        // 把所有数据都替换了
        const tempArr = []
        this.sheetData.sheetData.map(item => {
           const matchObj = subjectMap.get(item.subjectName)
           if (matchObj) {
            item.subjectName = matchObj.matchName
            tempArr.push(item)
           }
        })
        this.sheetData.sheetData = tempArr
      } else {
        this.sheetData.sheetData.map(item => {
           const matchObj = subjectMap.get(item.subjectName)
           if (matchObj && matchObj.matchName) {
            item.subjectName = matchObj.matchName
           }
        })
      }
      this.subjectDrawer = false
    },
    initBalanceTableData(drawer) {
      this.showEmptyRows = true
      this.subjectDrawer = drawer
      this.tableData = []
      const tempArr = []
      this.matchLoading = true
      this.sheetData.sheetData.map(subject => {
        let similaritySubject = this.findMostSimilarCourse(subject.subjectName)
        let status = 'warning'
        const exists = tempArr.some(item => item.matchName === similaritySubject)
        if (exists) {
          similaritySubject = ''
        }
        if (similaritySubject) {
          status = 'success'
        }
        const subjectObj = {
          subjectName: subject.subjectName,
          matchName: similaritySubject,
          status: status
        }
        tempArr.push(subjectObj)
      })
      this.tableData = tempArr
      this.matchLoading = false
      return tempArr
    },
    toggleEmptyRows() {
      this.showEmptyRows = !this.showEmptyRows
      if (this.showEmptyRows) {
        this.tableData = this.cacheTable
      } else {
        this.cacheTable = this.tableData
        const filteredArr = this.tableData.filter(item => item.matchName !== '' && item.subjectName !== '')
        this.tableData = filteredArr
      }
    }
    // exchangMoney(unit){
    //   this.cacheTable.map(item=>{
    //     item.
    //   })
    //   wordsMapLists[i]['amount'+i]
    //   for (let i = 0; i <= this.cacheTable.length; i++) {
    //           let wordsMap =  this.cacheTable[i].wordsMapLists
    //         for (let j = 0; j <= wordsMap.length; j++) {
    //           wordsMap[i].
    //         }
    //    }
    // }
  }
}
</script>

<style lang="scss" scoped>
.font-color-red /deep/.el-input__inner {
  color: red
}

.small-tag {
  // margin-right: 10px;
  // height: 20px;
  // line-height: 20px;
  // padding: 0px 1px;
  // font-size: 16px;
  // width: 20px;
}

.tag_contain {
  // margin: 24px 0px 24px 20px;
}

.bottom_contain {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.buttons {
  margin-bottom: 10px;
}

/* 修改行的最小高度 */
.dataForm .el-row .el-form-item {
  min-height: 0px;
}

::v-deep .ds-setting-drawer {
  /* 必须加上::v-deep，否则不生效 */
  right: 0px !important;
}

::v-deep .header-small-mb .el-drawer__header {
  margin-bottom: 6px;
}

::v-deep .header-small-mb .el-drawer__body {
  padding: 12px;
}

.drawer-title {
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}
</style>
